import '../models/community_post.dart';
import '../models/comment.dart';
import 'http_client.dart';

class CommunityService {
  final HttpClient _httpClient = HttpClient();

  // 辅助方法：安全获取响应数据
  Map<String, dynamic> _getResponseData(dynamic response) {
    if (response is Map<String, dynamic>) {
      return response;
    } else if (response.data is Map<String, dynamic>) {
      return response.data;
    } else {
      throw Exception('Invalid response format');
    }
  }

  /// 获取社区帖子列表
  Future<Map<String, dynamic>> getCommunityPosts({
    int page = 1,
    int size = 10,
    String? title,
    String? tags,
    String? location,
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/community/posts',
        queryParameters: {
          'pageNum': page,
          'pageSize': size,
          if (title != null && title.isNotEmpty) 'title': title,
          if (tags != null && tags.isNotEmpty) 'tags': tags,
          if (location != null && location.isNotEmpty) 'location': location,
        },
      );

      final responseData = _getResponseData(response);
      
      if (responseData['code'] == 200) {
        final data = responseData['data'] as List;
        
        final posts = <CommunityPost>[];
        for (int i = 0; i < data.length; i++) {
          try {
            final post = CommunityPost.fromJson(data[i]);
            posts.add(post);
          } catch (e) {
          }
        }
        
        
        return {
          'success': true,
          'data': posts,
          'total': posts.length,
          'message': responseData['msg'] ?? '获取成功',
        };
      } else {
        return {
          'success': false,
          'data': <CommunityPost>[],
          'message': responseData['msg'] ?? '获取失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': <CommunityPost>[],
        'message': '网络错误: $e',
      };
    }
  }

  /// 获取帖子详情
  Future<Map<String, dynamic>> getCommunityPostDetail(int postId) async {
    try {
      final response = await _httpClient.get('/pond/app/community/posts/$postId');
      final responseData = _getResponseData(response);

      if (responseData['code'] == 200) {
        final post = CommunityPost.fromJson(responseData['data']);
        return {
          'success': true,
          'data': post,
          'message': responseData['msg'] ?? '获取成功',
        };
      } else {
        return {
          'success': false,
          'data': null,
          'message': responseData['msg'] ?? '获取失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': null,
        'message': '网络错误: $e',
      };
    }
  }

  /// 发布新帖子
  Future<Map<String, dynamic>> createCommunityPost({
    required String title,
    required String content,
    List<String>? tags,
    String? location,
    List<String>? imageUrls,
  }) async {
    try {
      // 构建图片对象数组
      List<Map<String, dynamic>> imageObjects = [];
      if (imageUrls != null && imageUrls.isNotEmpty) {
        for (int i = 0; i < imageUrls.length; i++) {
          imageObjects.add({
            'imageUrl': imageUrls[i],
            'sortOrder': i + 1,
            'description': '', // 可以为空
          });
        }
      }

      final data = {
        'title': title,
        'content': Uri.encodeComponent(content), // URL编码内容
        'tags': tags != null ? tags.join(',') : '',
        'location': location ?? '',
        'images': imageObjects, // 发送图片对象数组而不是字符串
        'status': '1', // 已发布状态
      };

      final response = await _httpClient.post(
        '/pond/app/community/posts',
        data: data,
      );
      final responseData = _getResponseData(response);

      if (responseData['code'] == 200) {
        return {
          'success': true,
          'data': responseData['data'],
          'message': responseData['msg'] ?? '发布成功',
        };
      } else {
        return {
          'success': false,
          'data': null,
          'message': responseData['msg'] ?? '发布失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': null,
        'message': '网络错误: $e',
      };
    }
  }

  /// 更新帖子
  Future<Map<String, dynamic>> updateCommunityPost({
    required int postId,
    required String title,
    required String content,
    List<String>? tags,
    String? location,
  }) async {
    try {
      final data = {
        'id': postId,
        'title': title,
        'content': Uri.encodeComponent(content),
        'tags': tags != null ? tags.join(',') : '',
        'location': location ?? '',
      };

      final response = await _httpClient.put(
        '/pond/app/community/posts',
        data: data,
      );

      if (response.data['code'] == 200) {
        return {
          'success': true,
          'message': '更新成功',
        };
      } else {
        return {
          'success': false,
          'message': response.data['msg'] ?? '更新失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 删除帖子
  Future<Map<String, dynamic>> deleteCommunityPost(List<int> postIds) async {
    try {
      final idsString = postIds.join(',');
      final response = await _httpClient.delete('/pond/app/community/posts/$idsString');

      if (response.data['code'] == 200) {
        return {
          'success': true,
          'message': '删除成功',
        };
      } else {
        return {
          'success': false,
          'message': response.data['msg'] ?? '删除失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 点赞/取消点赞帖子
  Future<Map<String, dynamic>> toggleLikePost(int postId) async {
    try {
      final response = await _httpClient.post('/pond/app/community/posts/$postId/like');
      final responseData = _getResponseData(response);

      if (responseData['code'] == 200) {
        return {
          'success': true,
          'data': responseData['data'],
          'message': responseData['msg'] ?? '操作成功',
        };
      } else {
        return {
          'success': false,
          'message': responseData['msg'] ?? '操作失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 收藏/取消收藏帖子
  Future<Map<String, dynamic>> toggleFavoritePost(int postId) async {
    try {
      final response = await _httpClient.post('/pond/app/community/posts/$postId/favorite');

      if (response.data['code'] == 200) {
        return {
          'success': true,
          'data': response.data['data'],
          'message': '操作成功',
        };
      } else {
        return {
          'success': false,
          'message': response.data['msg'] ?? '操作失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 增加帖子阅读量
  Future<void> incrementReadCount(int postId) async {
    try {
      await _httpClient.post('/pond/app/community/posts/$postId/read');
    } catch (e) {
      // 阅读量增加失败不影响用户体验，静默处理
    }
  }

  /// 获取帖子评论列表
  Future<Map<String, dynamic>> getPostComments({
    required int postId,
    int page = 1,
    int size = 20,
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/community/posts/$postId/comments',
        queryParameters: {
          'pageNum': page,
          'pageSize': size,
        },
      );

      final responseData = _getResponseData(response);

      if (responseData['code'] == 200) {
        final data = responseData['data'] as List;
        
        return {
          'success': true,
          'data': data, // 直接返回原始数据，让组件自己解析
          'total': data.length,
          'message': responseData['msg'] ?? '获取成功',
        };
      } else {
        return {
          'success': false,
          'data': <Comment>[],
          'message': responseData['msg'] ?? '获取失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': <Comment>[],
        'message': '网络错误: $e',
      };
    }
  }

  /// 发表评论
  Future<Map<String, dynamic>> addComment({
    required int postId,
    required String content,
    int? parentId,
  }) async {
    try {
      String url;
      String successMessage;
      
      if (parentId != null) {
        // 回复评论
        url = '/pond/app/community/posts/$postId/comment/$parentId/reply';
        successMessage = '回复成功';
      } else {
        // 普通评论
        url = '/pond/app/community/posts/$postId/comment';
        successMessage = '评论成功';
      }

      final response = await _httpClient.post(
        url,
        data: {
          'content': content,
        },
      );

      final responseData = _getResponseData(response);

      if (responseData['code'] == 200) {
        return {
          'success': true,
          'data': responseData['data'],
          'message': successMessage,
        };
      } else {
        return {
          'success': false,
          'message': responseData['msg'] ?? (parentId != null ? '回复失败' : '评论失败'),
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 删除评论
  Future<Map<String, dynamic>> deleteComment(int commentId) async {
    try {
      final response = await _httpClient.delete('/pond/app/community/posts/comment/$commentId');

      final responseData = _getResponseData(response);

      if (responseData['code'] == 200) {
        return {
          'success': true,
          'message': '删除成功',
        };
      } else {
        return {
          'success': false,
          'message': responseData['msg'] ?? '删除失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 点赞/取消点赞评论
  Future<Map<String, dynamic>> toggleLikeComment(int commentId) async {
    try {
      final response = await _httpClient.post('/pond/app/community/posts/comment/$commentId/like');

      final responseData = _getResponseData(response);

      if (responseData['code'] == 200) {
        return {
          'success': true,
          'data': responseData['data'],
          'message': '操作成功',
        };
      } else {
        return {
          'success': false,
          'message': responseData['msg'] ?? '操作失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '网络错误: $e',
      };
    }
  }

  /// 获取热门帖子
  Future<Map<String, dynamic>> getHotPosts({
    int limit = 10,
    String type = 'read', // read, like, comment
  }) async {
    try {
      
      final response = await _httpClient.get(
        '/pond/app/community/posts/hot',
        queryParameters: {
          'limit': limit,
          'type': type,
        },
      );
      

      
      // 检查响应数据结构
      if (response is Map) {
        final responseMap = response as Map<String, dynamic>;
        if (responseMap.containsKey('data')) {
          if (responseMap['data'] is List) {
          }
        }
      }

      if (response['code'] == 200) {
        final data = response['data'] as List? ?? [];
        
        final posts = <CommunityPost>[];
        for (int i = 0; i < data.length; i++) {
          try {
            final post = CommunityPost.fromJson(data[i]);
            posts.add(post);
          } catch (e) {
          }
        }
        
        
        return {
          'success': true,
          'data': posts,
          'message': response['msg'] ?? '获取成功',
        };
      } else {
        return {
          'success': false,
          'data': <CommunityPost>[],
          'message': response['msg'] ?? '获取失败',
        };
      }
    } catch (e) {
      if (e.toString().contains('DioException')) {
      }
      return {
        'success': false,
        'data': <CommunityPost>[],
        'message': '网络错误: $e',
      };
    }
  }

  /// 获取用户收藏的帖子
  Future<Map<String, dynamic>> getUserFavorites({
    int page = 1,
    int size = 10,
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/community/posts/favorites',
        queryParameters: {
          'pageNum': page,
          'pageSize': size,
        },
      );

      if (response.data['code'] == 200) {
        final rows = response.data['rows'] as List;
        final posts = rows.map((json) => CommunityPost.fromJson(json)).toList();
        
        return {
          'success': true,
          'data': posts,
          'total': response.data['total'] ?? 0,
          'message': '获取成功',
        };
      } else {
        return {
          'success': false,
          'data': <CommunityPost>[],
          'message': response.data['msg'] ?? '获取失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': <CommunityPost>[],
        'message': '网络错误: $e',
      };
    }
  }

  /// 获取用户发布的帖子
  Future<Map<String, dynamic>> getUserPosts({
    int page = 1,
    int size = 10,
  }) async {
    try {
      final response = await _httpClient.get(
        '/pond/app/community/posts/my',
        queryParameters: {
          'pageNum': page,
          'pageSize': size,
        },
      );

      if (response.data['code'] == 200) {
        final rows = response.data['rows'] as List;
        final posts = rows.map((json) => CommunityPost.fromJson(json)).toList();
        
        return {
          'success': true,
          'data': posts,
          'total': response.data['total'] ?? 0,
          'message': '获取成功',
        };
      } else {
        return {
          'success': false,
          'data': <CommunityPost>[],
          'message': response.data['msg'] ?? '获取失败',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'data': <CommunityPost>[],
        'message': '网络错误: $e',
      };
    }
  }

  /// 获取用户的社区评论
  Future<List<Comment>> getUserComments({
    int page = 1,
    int size = 20,
  }) async {
    try {
      // 先尝试调用专门的用户评论API
      try {
        final response = await _httpClient.get(
          '/pond/app/user/comments/posts',
          queryParameters: {
            'pageNum': page,
            'pageSize': size,
          },
        );

        final responseData = _getResponseData(response);
        
        if (responseData['code'] == 200) {
          final data = responseData['data'];
          if (data is List) {
            return data.map((json) => Comment.fromJson(json)).toList();
          } else if (data is Map && data['rows'] != null) {
            return (data['rows'] as List).map((json) => Comment.fromJson(json)).toList();
          }
        }
      } catch (apiError) {
        // 如果专门的API不存在，返回空列表
        // 在实际应用中，这里可以实现其他获取逻辑
        return [];
      }
      
      return [];
    } catch (e) {
      return []; // 返回空列表而不是抛出异常
    }
  }
}